#region Usings

using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using RailNet.Dao.Entity;

#endregion

namespace RailNet.Dao.Repository
{
    public class DistanceRepository : IDistanceRepository
    {
        private readonly RailnetContext _context = new RailnetContext();

        #region IDistanceRepository Members

        public IQueryable<Distance> All
        {
            get { return _context.Distances; }
        }

        public IQueryable<Distance> AllIncluding(params Expression<Func<Distance, object>>[] includeProperties)
        {
            IQueryable<Distance> query = _context.Distances;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public IQueryable<Distance> AllIncludingDefault(params Expression<Func<Distance, object>>[] includeProperties)
        {
            IQueryable<Distance> query = _context.Distances;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Distance Find(long id)
        {
            return _context.Distances.Find(id);
        }

        public Distance Find(Station s1, Station s2)
        {
            return All.SingleOrDefault(d => (d.Station1.Id == s1.Id && d.Station2.Id == s2.Id) || (d.Station1.Id == s2.Id && d.Station2.Id == s1.Id));
        }

        public void InsertOrUpdate(Distance distance)
        {
            if (distance.Id == default(long))
            {
                // New entity
                _context.Distances.Add(distance);
            }
            else
            {
                // Existing entity
                _context.Entry(distance).State = EntityState.Modified;
            }
        }

        public void Delete(long id)
        {
            var distance = _context.Distances.Find(id);
            _context.Distances.Remove(distance);
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        #endregion
    }
}